<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <!-- //添加角色列表区域 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
                </el-col>
            </el-row>

            <!-- 角色列表区域 -->
            <el-table :data= "rolesList" border stripe>
                <!-- 展开列 -->         
                <el-table-column type="expand">
                     <!-- 自定义输出格式要用插槽 -->
                    <!-- eslint-disable-next-line -->
                    <template slot-scope="slotprops"> 
                        <!-- 栅格布局组件 -->
                        <el-row :class="['bdbottom', index == 0?'bdtop':'','vcenter']" :key = " item.id" v-for = "(item,index) in slotprops.row.children" >
                            <!-- 渲染以及权限 -->
                            <el-col :span = "5">
                                <el-tag closable @close ="removeRightById(slotprops.row,item2.id)" >{{item.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级三级权限 -->
                            <el-col :span = "19">
                                <!-- 通过for循环渲染二级权限 -->
                                <el-row :key="item1.id" v-for="(item1,index2) in item.children" :class="[index2 ==0?'':'bdtop','vcenter']">
                                    <el-col :span="6">
                                        <el-tag type="success" closable  @close ="removeRightById(slotprops.row,item1.id)" >{{item1.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag :key = 'item2.id' v-for="(item2) in item1.children" type="warning" closable @close ="removeRightById(slotprops.row,item2.id)">{{item2.authName}}</el-tag>

                                    </el-col>
                                </el-row>
                            </el-col>

                        </el-row>
                        <!-- <pre>{{slotprops.row}}</pre> -->
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column label="#" type="index" ></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                     <!-- 自定义输出格式要用插槽 -->
                    <!-- eslint-disable-next-line -->
                    <template slot-scope="slotprops">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRole(slotprops.row)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRole(slotprops.row.id)">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(slotprops.row)">分配权限</el-button>
                    </template>
                </el-table-column>

            </el-table>
        </el-card>

        <!-- 分配权限模块 -->
         <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close = "setRightsDialogClose">
            <!-- 树形控件 -->
            <el-tree :data=" rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys = 'defKeys' ref="treeRef"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible= false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 添加角色模块 -->
        <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close = "addDialogClose">
            <span>
                <el-form :model="addRolesForm" :rules="addRolesRules" ref="addRolesFormRef" label-width="100px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="addRolesForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="addRolesForm.roleDesc"></el-input>
                    </el-form-item>
                </el-form>    
            </span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRoles">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑角色模块 -->
        <el-dialog title="添加角色" :visible.sync="editDialogVisible" width="50%" @close = "editDialogClose">
            <span>
                <el-form :model="editRolesForm" :rules="editRolesRules" ref="editRolesFormRef" label-width="100px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="editRolesForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="editRolesForm.roleDesc"></el-input>
                    </el-form-item>
                </el-form>    
            </span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRoles">确 定</el-button>
            </span>
        </el-dialog>

      
        
    </div>
</template>

<script>


export default {
    data:function(){
        return{
            rolesList:[],
            addDialogVisible : false,
           
            // 添加角色表单
            addRolesForm:{
                roleName:'',
                roleDesc:'' 
            },
            //添加角色验证规则
            addRolesRules:{
                roleName:[
                    { required: true, message: '请输入角色名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                roleDesc:[
                    {required:false,message:'请输入角色描述',trigger:'blur'}
                ]
            },
             //分配权限
            setRightDialogVisible:false,
            // 所有权限数据
            rightsList:[],
            //树形控件的绑定对象
            treeProps:{
                label:'authName',
                children:'children'
            },
            //默认选中的Id数组
            defKeys:[],
            //当前即将分配角色的id
            roleId:'', 
            //控制编辑角色对话框的显示和隐藏
            editDialogVisible:false,
            // 编辑角色表单
            editRolesForm:{
                roleName:'',
                roleDesc:'',
            },
            //编辑角色验证规则
            editRolesRules:{
                roleName:[
                    { required: true, message: '请输入角色名', trigger: 'blur' },
                ],
                roleDesc:[
                    {required:false,message:'请输入角色描述',trigger:'blur'}
                ]
            },
        }
    },
    created(){
        this.getRolesList()
    },
    methods:{
        // 获取所有角色列表
        getRolesList: async function(){
            const {data:res} = await this.$http.get('roles');
            if(res.meta.status!==200){
                return this.$message.error('获取列表失败');
            }else{
                this.rolesList = res.data;
                console.log(res.data);
            }
        },
        //添加角色
        addRoles:async function(){
            const {data:res} = await this.$http.post('roles',this.addRolesForm);
            if(res.meta.status !==201){
                return this.$message.error('添加角色失败');

            }else{
                console.log(res.data);
                this.addRolesForm = res.data;
                this.getRolesList();
                this.addDialogVisible= false;
            }  
        },
        //角色添加对话框关闭事件
        addDialogClose:function(){
            console.log(this.$refs);
            this.$refs.addRolesFormRef.resetFields();
        }, // 根据ID删除对应的权限
        removeRightById: async function(role,rightId){
            // 弹框提示是否删除
            const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err=>err)
                if(res !='confirm'){
                    this.$message.info('取消了删除')
                }else{
                   const {data:res}= await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
                   if(res.meta.status!== 200){
                       this.$message.error('删除失败')
                   }else{
                    //    this.getRolesList()
                    // 防止页面刷新，提高用户体验
                    role.children = res.data
                   }
                }
        },
        // 展示分配权限对话框
        showSetRightDialog:async function(role){
        this.roleId = role.id
           const {data:res} = await this.$http.get(`rights/tree`)
           if(res.meta.status!== 200){
               this.$message.error('获取权限失败')
           }else{
                this.rightsList  = res.data
                console.log(res);
           }
           //递归获取三级节点id
           this.getLeafKeys(role,this.defKeys)
           this.setRightDialogVisible  = true
        },
        // 通过递归的形式，获取所有角色下的三级权限的id，并保存到defKeys数组中
        getLeafKeys:function(node,arr){
            // 如果当前node节点不包含children属性则是三级节点
            if( !node.children){
                return arr.push(node.id)

            }else{
                node.children.forEach(item => {
                    this.getLeafKeys(item,arr)                
                })
            }
        },
        //监听分配权限的监听事件
        setRightsDialogClose:function(){
            // 重置数组
            this.defKeys =[];
        },
        allotRights: async function(){
            const keys = [
                // ... 展开运算符 将一个数组展开成逗号隔开的序列
                ...this.$refs.treeRef.getCheckedKeys(),
                this.$refs.treeRef.getHalfCheckedKeys()
            ]
            // console.log(this.$refs);
            // console.log(keys);
            const idStr = keys.join(',');
            const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr});
            if(res.meta.status!==200){
                return this.$message.error('分配权限失败')
            }else{
                this.$message.success('分配权限成功');
                this.getRolesList();
                 this.setRightDialogVisible  = false;
            }
        },
        //角色编辑事件
        editRole:async function(role){
            const {data:res} = await this.$http.get(`roles/${role.id}`);
            // console.log(role.id);
            if(res.meta.status!==200){
                return this.$message.error('角色获取失败')
            }else{
                // console.log(res.data);
                this.editRolesForm = res.data;
            }
            this.editDialogVisible = true
        },
        //角色编辑后提交事件
        addRoles:function(){
            // 表单预验证
            console.log(this.$refs);
            this.$refs.editRolesFormRef.validate( async valid=>{
                if(!valid){
                    return
                }else{
                    //提交表单那
                    const {data:res} = await this.$http.put(`roles/${this.editRolesForm.roleId}`,{
                        roleName:this.editRolesForm.roleName,
                        roleDesc:this.editRolesForm.roleDesc,

                    })
                    console.log(res);
                    if(res.meta.status!==200){
                        return this.$message.error('角色更新失败')
                    }else{
                        this.$message.success('角色更新成功');
                        this.getRolesList()
                        this.editDialogVisible = false
                    }
                }
            })
        },
        //监听编辑角色对话框关闭事件
        editDialogClose:function(){
             this.$refs.editRolesFormRef.resetFields();
        },
        //删除角色
        deleteRole:async function(id){
            const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error=>{
                return error
            })
                // 如果用户确认删除返回字符串 confirm
                // 如果用户取消删除返回字符串 cancel
            if(res!='confirm'){
                return this.$message.info('已经取消删除！')
            }else{
                const {data:res}= await this.$http.delete(`roles/${id}`);
                if(res.meta.status !=200){
                    this.$message.error('删除失败！')
                }else{
                    this.$message.success('已经删除！');
                    this.getRolesList()
                }
            }
        }
         
        

    }
}
</script>

<style lang="less" scoped>
    .el-tag {
        margin: 7px;
    }
    .bdtop {
        border-top: 1px solid #eee;
    }
    .bdbottom {
        border-bottom: 1px solid #eee;
    }
    .vcenter {
        display: flex;
        align-items: center;
    }
</style>